package sjc;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

public class NodeCachedDemo {
    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3, Integer.MAX_VALUE);
        final CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.72.133:2181", 3000, 3000, retryPolicy);
        client.start();

        System.out.println("完成zookeeper的链接。。");

        final NodeCache nodeCache = new NodeCache(client, "/cluster");

        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                Stat stat = client.checkExists().forPath("/cluster");
                if(stat != null){
                    byte[] bytes = client.getData().forPath("/cluster");
                    System.out.println("节点数据发生了变化：" + new String(bytes));
                }else{
                    System.out.println("节点被删除 。。。。");
                }
            }
        });

        nodeCache.start();

        System.out.println("已经完成节点监听器的注册。。。。");

        Thread.sleep(Integer.MAX_VALUE);
    }
}
